package com.chat.module.message.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.comment.exception.ServiceException;
import com.chat.config.dao.RedisUtils;
import com.chat.config.web.webSocket.handler.WebSocketChannelManager;
import com.chat.module.message.mapper.WsMessageMapper;
import com.comment.pojo.domain.chat.WsMessage;
import com.comment.dubbo.service.ChatService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;

/**
 * 聊天服_服务
 */
@Slf4j
@Service
@DubboService(interfaceClass = ChatService.class)
public class WsMessageService extends ServiceImpl<WsMessageMapper, WsMessage>
        implements ChatService {
    @Resource
    private RedisUtils redisUtils;
    /**
     * 记录信息以及分类
     */
    public void messageLogByCode(WsMessage wsMessage) {
        Integer code = wsMessage.getCode();
        if (code != 3 && code != 4) {
            boolean save = save(wsMessage);
            if (save) {
                Long id = wsMessage.getId();
                String keyCode = String.format("wsMessage:%d", code);
                redisUtils.lRightPush(keyCode, id);
                redisUtils.lRightPush("wsMessage", JSONObject.toJSONString(wsMessage));
                log.info("消息日志:{},消息索引:{}，信息类型：{}", wsMessage, id, code);
            }
        }
    }

    public static HashSet<WsMessage> messageGetByCode(Integer code, Long size) {

        RedisUtils redisUtils = RedisUtils.redisUtils();

        String keyCode = String.format("wsMessage:%d", code);
        Long len = redisUtils.lLen(keyCode);

        HashSet<WsMessage> set = new HashSet<>();
        for (Object id : RedisUtils.redisUtils().lRange(keyCode, len - size, len)) {
            String key1 = "wsMessage";
            long key2 = Long.parseLong(id.toString()) - 1;
            WsMessage wsMessage = (WsMessage) redisUtils.lIndex(key1, key2);
            wsMessage.setCode(null);
            set.add(wsMessage);
        }
        return set;
    }

    public static WsMessage messageGetById(Integer id) {
        RedisUtils redisUtils = RedisUtils.redisUtils();
        String key = "wsMessage";
        return (WsMessage) redisUtils.lIndex(key, id - 1);
    }


    @Override
    public long obtainChatServiceAllOnline() {
        return WebSocketChannelManager.channelGroup.size();
    }

    @Override
    public void sendMessageToUser(Long userId, Object message) {
        String jsonString;
        try {
            jsonString = JSONObject.toJSONString(message);
        } catch (Exception e) {
            jsonString = message.toString();
        }
        Channel channel = WebSocketChannelManager.channelMap.get(userId);
        if (channel == null) {
            throw new ServiceException("用户不在线");
        }
        channel.writeAndFlush(new TextWebSocketFrame(jsonString));
    }

    @Override
    public void sendMessageAll(WsMessage wsMessage) {
        WebSocketChannelManager.channelGroup.writeAndFlush(
                new TextWebSocketFrame(JSONObject.toJSONString(wsMessage)));
    }


    @Resource
    private WsMessageMapper wsMessageMapper;

    // 备份任务
    public void backUpTask() {
        log.info("开始备份聊天记录");

    }
}
